package com.gy.api.mobile.company.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.gy.api.base.*;
import com.gy.api.mobile.company.domain.vo.*;
import com.gy.api.mobile.company.service.ICompanyService;
import com.gy.api.mobile.user.domain.vo.UpdateUserPasswordVO;
import com.gy.api.sms.req.SendCodeValidateVO;
import com.gy.api.sms.service.DynamicMessageService;
import com.gy.exception.BusinessException;
import com.gy.util.BindingResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/h5/company")
@Api( tags = ApiIndex.H5_CompanyController)
@Slf4j
public class CompanyController {

    @Autowired
    private ICompanyService service;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private DynamicMessageService smsService;


    @ApiOperation("企业登录(账号密码都需要加密传入)")
    @PostMapping("/login")
    public R<CompanyLoginResVO> login(@RequestBody CompanyLoginVO companyLoginVO, BindingResult bindingResult) {
        R result= BindingResultUtil.BindingResult(bindingResult);
        if(result.getCode()== Constants.SYS_SUCCESS){
            CompanyLoginResVO userLoginResVO = service.login(companyLoginVO);
            result.setData(userLoginResVO);
        }
        return result;
    }

    @ApiOperation("退出登录")
    @PostMapping("/login_out")
    @SaCheckLogin
    public R loginOut(){
        StpUtil.logout();
        return new R();
    }

    @ApiOperation("查询当前企业信息")
    @GetMapping("/one")
    @SaCheckLogin
    public R<CompanyVO> getOne(){
        CompanyVO userVO=service.getCompanyOne();
        return new R(userVO);
    }


    @ApiOperation("查询当前企业信息详情")
    @GetMapping("/one_desc")
    @SaCheckLogin
    public R<CompanyInfoVO> getOneDesc(){
        CompanyInfoVO userVO=service.getCompanyDesc(StpUtil.getLoginIdAsString());
        return new R(userVO);
    }


    @ApiOperation("注册企业信息")
    @PostMapping("/register")
    public R register(@RequestBody CompanyAddVO companyAddVO) throws Exception {
        String code= redisUtils.get(Constants.CAPTCHA_CODE_KEY +"_"+companyAddVO.getUserPhone()+"_"+1);
        if(StringUtils.isEmpty(code)){
            throw new BusinessException(Type.FAIL.getCode(),"短信验证码不正确或已失效！");
        }
        if(!code.equals(companyAddVO.getPhoneCode())){
            throw new BusinessException(Type.FAIL.getCode(),"短信验证码不正确！");
        }
        redisUtils.delete(Constants.CAPTCHA_CODE_KEY +"_"+companyAddVO.getUserPhone()+"_"+1);
         service.registerCompany(companyAddVO);
         return new R();
    }

    @ApiOperation("找回密码-更新企业密码")
    @PostMapping("/update_password")
    public R updateCompanyPasswordVO(@RequestBody UpdateCompanyPasswordVO passwordVO) throws Exception {
        service.updateCompanyPasswordVO(passwordVO);
        return new R();
    }


    @ApiOperation("更新用户密码(通过旧密码)")
    @PostMapping("/update_old_password")
    @SaCheckLogin
    public R update_old_password(@RequestBody UpdateUserPasswordVO updateUserPasswordVO) throws Exception {
        service.updateOldPassword(updateUserPasswordVO);
        return new R();
    }

    @ApiOperation("找回密码-验证企业信用代码")
    @PostMapping("/validate_company_code")
    public R<CompanyVO> validate_company_code(@RequestBody CompanyValidateCodeVO validateCodeVO){
        return service.validate_company_code(validateCodeVO.getCompanyCreditCode());
    }


    @ApiOperation("发起-企业办事认证")
    @PostMapping("/authentication")
    @SaCheckLogin
    public R<CompanyVO> authentication(@RequestBody CompanyAuthenticationVO companyAuthenticationVO) throws Exception {
        service.authentication(companyAuthenticationVO);
        return new R();
    }

    @ApiOperation("发送短信")
    @PostMapping("/send_code")
    public R send_code(@ApiParam(value = "参数")  @RequestBody CompanySendCodeVO sendCodeVO){
        String code= RandomUtil.randomNumbers(4);
        log.info(sendCodeVO.getPhone()+":::::发送短信验证码::::"+code);
        redisUtils.set(Constants.CAPTCHA_CODE_KEY +"_"+sendCodeVO.getPhone()+"_"+sendCodeVO.getSmsType(),code,60*30, TimeUnit.SECONDS);
        try{

            switch (sendCodeVO.getSmsType()){
                case 1:
                    smsService.sendDynamicMessage("【光影重庆】您好，您此次验证码为:"+code+"，请不要把验证码泄漏给其他人，如非本人请勿操作。",sendCodeVO.getPhone());
                    break;
                case 2:
                    smsService.sendDynamicMessage("【光影重庆】您正在找回密码，验证码为："+code+"，请不要把验证码泄露给其他人。如非本人操作，可不用理会！",sendCodeVO.getPhone());
                    break;
            }

        }catch (Exception e){
//            e.printStackTrace();
            return  new R(code);
        }
        return new R();
    }

    @ApiOperation("验证短信验证码")
    @PostMapping("/validate_code")
    public R<String> validate_code(@ApiParam(value = "参数")  @RequestBody SendCodeValidateVO validateVO)  {
        String code= redisUtils.get(Constants.CAPTCHA_CODE_KEY +"_"+validateVO.getPhone()+"_"+validateVO.getSmsType());
        if(StringUtils.isEmpty(code)){
            throw new BusinessException(Type.FAIL.getCode(),"短信验证码不正确或已失效！");
        }
        if(!code.equals(validateVO.getCode())){
            throw new BusinessException(Type.FAIL.getCode(),"短信验证码不正确！");
        }
        redisUtils.delete(Constants.CAPTCHA_CODE_KEY +"_"+validateVO.getPhone()+"_"+validateVO.getSmsType());
        return new R();
    }

    @ApiOperation("验证企业信息是否认证中（返回成功未认证）")
    @PostMapping("/validate_company")
    public R validate_company(@ApiParam(value = "参数")  @RequestBody CompanyValidateVO validateVO)  {
        service.validateCompany(validateVO);
        return new R();
    }

    @ApiOperation("验证企业信息是否认证成功（返回成功 认证成功）")
    @PostMapping("/validate_company_state")
    public R validate_company_state(@ApiParam(value = "参数")  @RequestBody CompanyValidateVO validateVO)  {
        service.validateCompanyState(validateVO);
        return new R();
    }

    @ApiOperation("本地调试-导入企业信息")
    @GetMapping("/import_excel")
    public R import_excel(){
        service.import_excel();
        return new R();
    }


}
